import { strIsEmpty,
          objIsNull,
          listIsEmpty,
        } from '../valid/valid_util'

const recoverVuexObj = function (state, key) {
  const json = sessionStorage.getItem(key)
  if(strIsEmpty(json)) {
    state[key] = {}
    return
  }

  const obj = JSON.parse(json)
  if(objIsNull(obj)) {
    state[key] = {}
  }

  state[key] = obj
}

const recoverVuexValue = function (state, key) {
  const value = sessionStorage.getItem(key)

  state[key] = value
}

const recoverVuexList = function (state, key) {
  const json = sessionStorage.getItem(key)
  if(strIsEmpty(json)) {
    state[key] = []
  }

  const list = JSON.parse(json)
  if(listIsEmpty(list)) {
    state[key] = []
  }

  state[key] = list
}

// 从SessionStorage中恢复Vuex
const recoverVuex = function (state) {

  // 遍历state对象的所有属性名
  for(let key in state){
    //取出属性
    const property = state[key]
    //属性是数组
    if(Array.isArray(property))
      recoverVuexList(state, key)

    switch(typeof(property)) {
      //属性是对象
      case 'object':
        recoverVuexObj(state, key)
        break
      //属性是字符串、数字、布尔
      case 'string':
      case 'number':
      case 'boolean':
        recoverVuexValue(state, key)
        break
      // 属性是"function"、"undefined"
      default:
        break
    }
  }
}

// 将任意变量存入SessionStorage
const saveInSessionStorage = function(prop, key) {
  const kind = typeof(prop)
  switch(kind) {
    case 'object': {
      const json = JSON.stringify(prop)
      sessionStorage.setItem(key, json)
      break
    }
    case 'string':
    case 'number':
    case 'boolean':
      sessionStorage.setItem(key, prop)
      break
    default:
      break
  }
}

export {
  recoverVuex,
  saveInSessionStorage
}